package com.antdesignbackend.backend.common.http;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class HttpClientUtils {
    // 编码格式。发送编码格式统一用UTF-8
    private static final String ENCODING = "UTF-8";
    // 设置连接超时时间，单位毫秒。
    private static final int CONNECT_TIMEOUT = 6000;
    // 请求获取数据的超时时间(即响应时间)，单位毫秒。
    private static final int SOCKET_TIMEOUT = 10000;

    /**
     * 初始化配置
     *
     * @param proxyIp          代理ip
     * @param proxyPort        代理端口
     * @param redirectsEnabled 重定向，默认true，遇到支付链接直接跳转的，httpclient源码写的好像有问题
     * @return
     */
    private static RequestConfig getRequestConfig(String proxyIp, int proxyPort, boolean redirectsEnabled) {
        RequestConfig requestConfig = null;
        RequestConfig.Builder builder = RequestConfig.custom();
        builder.setConnectTimeout(CONNECT_TIMEOUT); //设置连接超时时间，单位毫秒
        builder.setSocketTimeout(SOCKET_TIMEOUT); //请求获取数据的超时时间(即响应时间)，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
        builder.setRedirectsEnabled(redirectsEnabled);
        if (!proxyIp.equals("")) {
            HttpHost httpHost = new HttpHost(proxyIp, proxyPort);
            builder.setProxy(httpHost);
        }
        requestConfig = builder.build();
        return requestConfig;
    }


    /**
     * 发送get请求；核心方法
     * 代理ip
     * 代理端口
     *
     * @param url
     * @param headers
     * @param params
     * @param proxyIP
     * @param proxyPort
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params, String proxyIP, int proxyPort, boolean redirectsEnabled) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = doGetHandle(url, headers, params, proxyIP, proxyPort, redirectsEnabled);
        return getHttpClientResult(httpClient, httpGet, null, false);
    }

    public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params, String proxyIP, int proxyPort, boolean redirectsEnabled, boolean isStream) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = doGetHandle(url, headers, params, proxyIP, proxyPort, redirectsEnabled);
        return getHttpClientResult(httpClient, httpGet, null, isStream);
    }

    /**
     * 发送get请求；核心方法
     */
    public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params, boolean redirectsEnabled) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = doGetHandle(url, headers, params, "", -1, redirectsEnabled);
        return getHttpClientResult(httpClient, httpGet, null, false);
    }

    /**
     * 发送Post请求；核心方法
     * 代理ip
     * 代理端口
     */
    public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params, RequestType requestType, String proxyIP, int proxyPort, boolean redirectsEnabled) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = doPosthandle(url, headers, params, requestType, proxyIP, proxyPort, redirectsEnabled);
        return getHttpClientResult(httpClient, httpPost, null, false);
    }

    /**
     * 发送Post请求；核心方法
     * 代理ip
     * 代理端口
     */
    public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params, RequestType requestType, String proxyIP, int proxyPort, boolean redirectsEnabled, boolean isStream) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = doPosthandle(url, headers, params, requestType, proxyIP, proxyPort, redirectsEnabled);
        return getHttpClientResult(httpClient, httpPost, null, isStream);
    }

    /**
     * 发送Post请求；核心方法
     */
    public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params, RequestType requestType, boolean redirectsEnabled) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = doPosthandle(url, headers, params, requestType, "", -1, redirectsEnabled);
        return getHttpClientResult(httpClient, httpPost, null, false);
    }

    /**
     * 发送Post请求；核心方法
     */
    public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params, RequestType requestType, boolean redirectsEnabled, boolean isStream) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = doPosthandle(url, headers, params, requestType, "", -1, redirectsEnabled);
        return getHttpClientResult(httpClient, httpPost, null, isStream);
    }


    /**
     * 发送get请求；不带请求头和请求参数
     *
     * @param url 请求地址
     * @throws Exception
     */
    public static HttpClientResult doGet(String url) throws Exception {
        return doGet(url, null, null, true);
    }

    /**
     * 发送get请求；带请求参数
     *
     * @param url    请求地址
     * @param params 请求参数集合
     * @throws Exception
     */
    public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
        return doGet(url, null, params, true);
    }


    /**
     * 发送post请求；不带请求头和请求参数
     *
     * @param url 请求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPost(String url) throws Exception {
        return doPost(url, null, null);
    }

    /**
     * 发送post请求；带请求参数
     *
     * @param url    请求地址
     * @param params 参数集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPost(String url, Map<String, String> params, RequestType requestType) throws Exception {
        return doPost(url, null, params, requestType, true);
    }


    /**
     * GET 请求handle方法
     *
     * @param url     请求地址
     * @param headers 请求头集合
     * @param params  请求参数集合
     * @return
     * @throws Exception
     */
    public static HttpGet doGetHandle(String url, Map<String, String> headers, Map<String, String> params, String proxyIP, int proxyPort, boolean redirectsEnabled) throws Exception {
        // 创建访问的地址
        URIBuilder uriBuilder = new URIBuilder(url);
        if (params != null) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }
        // 创建http对象
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.setConfig(getRequestConfig(proxyIP, proxyPort, redirectsEnabled));
        // 设置请求头
        packageHeader(headers, httpGet);
        return httpGet;
    }


    /**
     * POST handle方法
     *
     * @param url     请求地址
     * @param headers 请求头集合
     * @param params  请求参数集合
     * @throws Exception
     */
    public static HttpPost doPosthandle(String url, Map<String, String> headers, Map<String, String> params, RequestType requestType, String proxyIP, int proxyPort, boolean redirectsEnabled) throws Exception {
        // 创建http对象
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(getRequestConfig(proxyIP, proxyPort, redirectsEnabled));
        // 设置请求头
        packageHeader(headers, httpPost);
        // 封装请求参数
        packageParam(params, httpPost, requestType);
        // 执行请求并获得响应结果
        return httpPost;
    }


    /**
     * Description: 封装请求头
     *
     * @param params
     * @param httpMethod
     */
    public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
        // 封装请求头
        if (params != null) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                // 设置到请求头到HttpRequestBase对象中
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Description: 封装请求参数
     *
     * @param params
     * @param httpMethod
     * @throws UnsupportedEncodingException
     */
    public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod, RequestType requestType)
            throws UnsupportedEncodingException {
        // 封装请求参数
        if (params != null) {
            switch (requestType) {
                case JSON:
                    String jsonString = JSONObject.toJSONString(params);
                    System.out.println(jsonString);
                    StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
                    httpMethod.setEntity(entity);
                    break;
                case FORM_URLENCODED:
                    List<NameValuePair> nvps = new ArrayList<>();
                    Set<Map.Entry<String, String>> entrySet = params.entrySet();
                    for (Map.Entry<String, String> entry : entrySet) {
                        nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                    }

                    // 设置到请求的http对象中
                    httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
                    break;
                case FORM_URLENCODED_TEXT_HTML:
                    Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
                    Map.Entry<String, String> tail = null;
                    while (iterator.hasNext()) {
                        tail = iterator.next();
                        break;
                    }
                    StringEntity stringentity = new StringEntity(tail.getValue(), ContentType.create("text/html", "UTF-8"));
                    httpMethod.setEntity(stringentity);
                    break;
            }
        }
    }

    /**
     * 发送请求，处理请求数据
     */
    public static HttpClientResult getHttpClientResult(CloseableHttpClient httpClient, HttpRequestBase httpMethod, HttpClientContext httpClientContext, boolean isStream) {

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpMethod, httpClientContext);
            if (response == null || response.getStatusLine() == null) {
                return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            }
            Header[] cookie = response.getHeaders("Set-Cookie");
            for (int i = 0; i < cookie.length; i++) {
                System.out.println(cookie[i].getName());
                System.out.println(cookie[i].getValue());
            }

            if (isStream) {
                InputStream inputStream = response.getEntity().getContent();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                try {
                    if (inputStream != null) {
                        byte[] buffer = new byte[4096];
                        int length;

                        while ((length = inputStream.read(buffer)) > -1) {
                            byteArrayOutputStream.write(buffer, 0, length);
                        }

                        byteArrayOutputStream.flush();

                        return new HttpClientResult(response.getStatusLine().getStatusCode(), byteArrayOutputStream.toByteArray(), cookie);
                    }
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                } finally {

                    if (byteArrayOutputStream != null) {
                        byteArrayOutputStream.close();
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
            }

            String content = "";
            if (response.getEntity() != null) {
                content = EntityUtils.toString(response.getEntity(), ENCODING);
            }
            System.out.println("response:" + response);
            System.out.println("content:" + response);

            //重定向
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
                org.apache.http.Header locationHeader = response.getFirstHeader("Location");
                if (locationHeader != null) {
                    String location = locationHeader.getValue();
                    System.out.println("location:" + location);
                    return new HttpClientResult(response.getStatusLine().getStatusCode(), content, cookie, location);
                }
            }

            return new HttpClientResult(response.getStatusLine().getStatusCode(), content, cookie);

        } catch (Exception e) {
            e.printStackTrace();
            return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        } finally {
            try {
                release(response, httpClient);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Description: 释放资源
     *
     * @param httpResponse
     * @param httpClient
     * @throws IOException
     */
    public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        // 释放资源
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

